#coding:utf-8
import cv2
import numpy as np

def split_image(name, output):
    image = cv2.imread(name)
    # 二值化
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    binary = cv2.adaptiveThreshold(~gray, 255,
                                   cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 15, -10)
    cv2.imwrite('./temp/cell.jpg', binary)

    rows, cols = binary.shape
    scale = 20
    # 识别横线
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (cols // scale, 1))
    eroded = cv2.erode(binary, kernel, iterations=2)
    dilatedcol = cv2.dilate(eroded, kernel, iterations=2)
    cv2.imwrite('./temp/dilated1.jpg', dilatedcol)

    # 识别竖线
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, rows // scale))
    eroded = cv2.erode(binary, kernel, iterations=3)
    dilatedrow = cv2.dilate(eroded, kernel, iterations=3)
    cv2.imwrite('./temp/dilated2.jpg', dilatedrow)

    # 标识交点
    bitwiseAnd = cv2.bitwise_and(dilatedcol, dilatedrow)
    cv2.imwrite('./temp/bitwise.jpg', bitwiseAnd)

    # 标识表格
    merge = cv2.add(dilatedcol, dilatedrow)
    cv2.imwrite('./temp/add.jpg', merge)

    # 识别黑白图中的白色点
    ys, xs = np.where(bitwiseAnd > 0)
    mylisty = []
    mylistx = []

    # 通过排序，获取跳变的x和y的值，说明是交点，否则交点会有好多像素值，我只取最后一点
    i = 0
    myxs = np.sort(xs)
    # print('myxs', myxs)
    for i in range(len(myxs) - 1):
        if (myxs[i + 1] - myxs[i] > 60):
            mylistx.append(myxs[i])
        i = i + 1
    mylistx.append(myxs[i])
    print('纵向：', mylistx)
    # print(len(mylistx))

    i = 0
    myys = np.sort(ys)
    # print('myys', myys)

    for i in range(len(myys) - 1):
        if (myys[i + 1] - myys[i] > 20):
            mylisty.append(myys[i])
        i = i + 1
    mylisty.append(myys[i])
    if len(mylisty) < 3:
        if mylisty[0] > rows - mylisty[-1]:
            mylisty = [0] + mylisty
        else:
            mylisty.append(rows)
    print('横向', mylisty)
    # print(len(mylisty))

    for i in range(0, len(mylisty)-1):
        height = mylisty[i+1] - mylisty[i]
        # print(height)
        if height > 100:
            index = i

    label = []
    for i in range(len(mylisty) - 1):
        for n in range(len(mylistx) - 1):
        	# 缩小ROI范围，自定义浮动，让边缘切的更好一点
            ROI = image[mylisty[i]:mylisty[i + 1] - 7, mylistx[n]:mylistx[n + 1] - 10]
            img_name = output + "_%d_%d"%(i,n) + '.jpg'
            img_path = img_name
            label.append((mylistx[n], mylisty[i], mylistx[n + 1] - 10, mylisty[i + 1] - 5))
    return label


if __name__ == '__main__':
    split_image('./temp/items_bin.jpg', 'images')
